package mysql

import (
	"errors"
	"gitee.com/DonHz/qimi/bluebell/models"
	"gitee.com/DonHz/qimi/bluebell/util/encrypt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"reflect"
	"time"
)

var (
	ErrorUserExist = errors.New("用户已存在")
	ErrorUserNotExist = errors.New("用户不存在")
	ErrorInvalidPassword = errors.New("用户名或密码错误")
)


func FindByName(name string) {

}

func FindUserById(authorId int64) (string, error) {
	var user models.User
	err:=db.Select("name").Where("user_id=?",authorId).
		Find(&user).Error
	if err!=nil {
		zap.L().Error("通过用户ID查找用户失败", zap.Error(err))
		if err==gorm.ErrRecordNotFound {
			return "", ErrorUserNotExist
		}
		return "", err
	}
	return user.Name, nil
}

func CheckUserExist(name string) (bool, error) {
	var user models.User
	err:=db.Select("id").Where("name=?", name).Find(&user).Error
	if err!=nil {
		return false, ErrorUserExist
	}
	if reflect.DeepEqual(user, models.User{}){
		return false, nil
	}
	return true, nil
}

func Insert(user *models.User) error {
	// 对密码进行加密
	now:=time.Now().UnixMilli()
	user.CreateTime=now
	user.UpdateTime=now
	user.Password= encrypt.EncryptPassword(user.Password)
	return db.Create(user).Error
}

func Login(u *models.User) error {
	oPassword:=u.Password
	err:=db.Select("id, user_id, password").Where("name=?", u.Name).Find(&u).Error
	if err!=nil {
		zap.L().Error("登录过程数据库查询失败", zap.Error(err))
		if err==gorm.ErrRecordNotFound {
			return ErrorUserNotExist
		}
		return err
	}
	if u.Password!=oPassword {
		return ErrorInvalidPassword
	}
	return nil
}
